package com.raincat.tools.nettools;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Pair;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

/**
 * 网络连接类
 * Created by Administrator on 2018/3/29 0029.
 */

class Connect {
    ProgressDialog mProgressDialog;
    Request request = null;
    static ExecutorService exec = Executors.newFixedThreadPool(10);

    void init(Request request) {
        try {
            if (request.context.get() == null || (request.context.get() instanceof Activity) && ((Activity) request.context.get()).isFinishing())
                return;
            if (getNetType(request.context.get()) == -1) {
                NetStatusManager.getInstance(request.context.get()).addRequest(request);
                return;
            }
            if (request.context.get() instanceof Activity && request.dialogMessage.length() != 0
                    && (mProgressDialog == null || !mProgressDialog.isShowing()))
                mProgressDialog = ProgressDialog.show(request.context.get(), null, request.dialogMessage);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

        if (request.cookie.length() == 0)
            request.cookie = getCookie(request.context.get());

        this.request = request;
    }

    boolean getResult(Pair<Integer, String> result, AsyncTask<Request, Integer, Pair<Integer, String>> task) {
        try {
            if (request.context.get() == null) {
                if (mProgressDialog != null)
                    mProgressDialog.dismiss();
            } else if (result.first == 0) {
                if (mProgressDialog != null)
                    mProgressDialog.dismiss();
                if (request.back != null && !task.isCancelled()) {
                    request.back.result(result.second);
                }
            } else if (request.reTry > 0) {
                request.reTry--;
                return false;
            } else if (request.reTry == 0) {
                if (mProgressDialog != null)
                    mProgressDialog.dismiss();
                if (request.back != null && !task.isCancelled())
                    request.back.error(result.first, result.second);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * @return -1：没有网络 0：流量 1：WIFI
     */
    private int getNetType(Context context) {
        int netType = -1;
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connMgr == null)
            return netType;
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null)
            return netType;
        return networkInfo.getType();
    }

    /**
     * 获取cookie
     *
     * @param context 上下文
     * @return 返回值
     */
    private String getCookie(Context context) {
        SharedPreferences share = PreferenceManager.getDefaultSharedPreferences(context);
        return share.getString("Cookie", "");
    }

    /**
     * 保存cookie
     *
     * @param context 上下文
     * @param cookie  cookie
     */
    void saveCookie(Context context, String cookie) {
        SharedPreferences share = PreferenceManager.getDefaultSharedPreferences(context);
        share.edit().putString("Cookie", cookie).apply();
    }

    /**
     * 读取证书
     *
     * @param context        上下文
     * @param assetsFileName 证书路径
     * @return 返回值
     */
    SSLContext getSSLContext(Context context, String assetsFileName) {
        SSLContext sslContext = null;
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream in = context.getAssets().open(assetsFileName);
            Certificate ca = cf.generateCertificate(in);
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);
            keystore.setCertificateEntry("ca", ca);
            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keystore);
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(), null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sslContext;
    }
}
